import React from 'react';
import {ScrollView, View, Image, Text, StyleSheet} from 'react-native';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import FAIcon from 'react-native-vector-icons/FontAwesome5';
import * as profileActionCreator from '../../actions/profile-actions';
import * as authActionCreator from '../../actions/auth-actions';
import * as intlActionCreator from '../../actions/intl-actions';
import {getRealSize, Touchable} from '../../utils';
import ListItem from '../../components/list-item';
import Icon from '../../resource/iconfont';
import ThemeStyles from '../../styles';
import ConfirmDialog, {DialogMode} from '../../components/confirm-dialog';
import {I18n} from '../../reducers/intl';
import {connectActionSheet} from '@expo/react-native-action-sheet';
import _ from 'lodash';
import Tag from '../../components/tag';
import {UserType} from '../../reducers/user';
import InputDialog from '../../components/input-dialog';
import {NavigationActions, StackActions} from 'react-navigation';

class MyScreen extends React.Component {
  static navigationOptions = {
    header: null,
  };

  state = {
    dialog: {},
  };

  onShowNote = () => {
    const {user} = this.props;
    this.setState({
      dialog: {
        title: I18n.t('dialog.title.note'),
        content: user.intro,
        inputVisible: true,
        field: 'note',
      },
    });
  };

  onChangeLanguage = () => {
    const {intlActions, navigation} = this.props;
    const options = [];
    options.push(I18n.t('options.language.en'));
    options.push(I18n.t('options.language.zh'));
    options.push(I18n.t('button.cancel'));
    const cancelButtonIndex = 2;
    this.props.showActionSheetWithOptions(
      {
        options,
        cancelButtonIndex,
        textStyle: {flex: 1},
      },
      buttonIndex => {
        switch (buttonIndex) {
          case 0:
            intlActions.change('en');
            navigation.setParams({intl: 'en'});
            break;
          case 1:
            intlActions.change('zh');
            navigation.setParams({intl: 'zh'});
            break;
          default:
            break;
        }
      },
    );
  };

  onConfirm = () => {
    if (this.state.dialog.field === 'signOut') {
      this.onSignOut();
    }
  };

  onSignOutConfirm = () => {
    this.setState({
      dialog: {
        title: I18n.t('dialog.title.signOut'),
        content: I18n.t('dialog.content.confirmSignOut'),
        visible: true,
        field: 'signOut',
      },
    });
  };

  onSignOut = () => {
    const {authActions, navigation} = this.props;
    authActions.signOut();
    const resetAction = StackActions.reset({
      index: 0,
      actions: [
        NavigationActions.navigate({routeName: 'Auth'}), //要跳转到的页面名字
      ],
    });
    navigation.dispatch(resetAction);
  };

  onSubmit = (field, value) => {
    const {profileActions} = this.props;
    profileActions.updateContact({[field]: value});
  };

  render() {
    const {navigation, user, intl, device} = this.props;
    // console.log(JSON.stringify(user));
    return (
      <ScrollView style={Styles.container}>
        <View>
          <ProfileCard
            {...user}
            onPress={() => navigation.navigate('Profile')}
          />
        </View>
        <View>
          {[UserType.provider, UserType.technician].includes(user.type) && (
            <ListItem
              icon={
                <Icon name="molargonggao" size={getRealSize(24)} color="#000" />
              }
              label={I18n.t('menu.note')}
              onPress={this.onShowNote}
            />
          )}
          {[UserType.provider, UserType.technician].includes(user.type) && (
            <ListItem
              icon={
                <Icon name="molartupian" size={getRealSize(24)} color="#000" />
              }
              label={I18n.t('menu.album')}
              onPress={() => navigation.navigate('Album')}
            />
          )}
          <ListItem
            icon={
              <Icon name="molarguanlian" size={getRealSize(24)} color="#000" />
            }
            label={I18n.t('menu.associate')}
            onPress={() => navigation.navigate('Associate')}
          />
          {[UserType.clinic, UserType.dentist].includes(user.type) && (
            <ListItem
              icon={
                <Icon name="molarVIP" size={getRealSize(24)} color="#000" />
              }
              label={I18n.t('menu.service')}
              onPress={() => navigation.navigate('Service')}
            />
          )}
          <ListItem
            icon={<Icon name="molarmima" size={getRealSize(24)} color="#000" />}
            label={I18n.t('menu.changePwd')}
            onPress={() => navigation.navigate('Resetpwd')}
          />
          <ListItem
            icon={
              <Icon name="molaryuyan" size={getRealSize(24)} color="#000" />
            }
            label={I18n.t('menu.language')}
            extra={I18n.t(intl)}
            onPress={this.onChangeLanguage}
          />
          {[UserType.provider, UserType.technician].includes(user.type) && (
            <ListItem
              icon={
                <Icon name="molartupian" size={getRealSize(24)} color="#000" />
              }
              label={I18n.t('menu.productSetting')}
              onPress={() => navigation.navigate('ProductSetting')}
            />
          )}
          <ListItem
            icon={
              <Icon name="molarguanyu" size={getRealSize(24)} color="#000" />
            }
            label={I18n.t('menu.about')}
            onPress={() => navigation.navigate('About')}
          />
          <ListItem
            icon={
              <Icon name="molarguanyu" size={getRealSize(24)} color="#000" />
            }
            label={I18n.t('menu.signOut')}
            onPress={this.onSignOutConfirm}
          />
        </View>
        <ConfirmDialog
          title={this.state.dialog.title}
          content={this.state.dialog.content}
          visible={this.state.dialog.visible}
          cancelLabel={I18n.t('button.close')}
          okLabel={I18n.t('button.apply')}
          mode={DialogMode.confirm}
          onConfirm={this.onConfirm}
          onClose={() => this.setState({dialog: {visible: false}})}
        />
        <InputDialog
          visible={this.state.dialog.inputVisible}
          title={this.state.dialog.title}
          field="intro"
          cancelLabel={I18n.t('button.close')}
          okLabel={I18n.t('button.save')}
          defaultValue={user.intro || I18n.t('form.label.note')}
          onClose={() => this.setState({dialog: {inputVisible: false}})}
          onSubmit={value => this.onSubmit('intro', value)}
        />
        <View style={[Styles.bottomBarContainer]}>
          <Text style={Styles.bottomLabel}>js: v{device.jsVersion}</Text>
          <Text style={Styles.bottomLabel}>app: v{device.appVersion}</Text>
          <Text style={Styles.bottomLabel}>device: v{device.deviceId}</Text>
        </View>
      </ScrollView>
    );
  }
}

const ProfileCard = props => (
  <Touchable onPress={() => props.onPress()}>
    <View style={Styles.profileContainer}>
      <Image
        style={Styles.profileAvatar}
        source={{
          uri: _.get(props, 'avatar.url'),
        }}
      />
      <View style={Styles.profileContent}>
        <Tag
          label={I18n.t(`profile.approved.${props.approved ? 'yes' : 'no'}`)}
        />
        <Text style={Styles.profileTitle}>
          {props.vendor_name || props.clinic_name || props.email}
        </Text>
        <Text style={Styles.profileExtra}>{props.email}</Text>
      </View>
      <FAIcon name="chevron-right" color="#8F8F8F" size={getRealSize(14)} />
    </View>
  </Touchable>
);

const mapStateToProps = state => ({
  appState: state.appState,
  user: state.user,
  profile: state.profile,
  device: state.device,
  intl: state.intl,
  nav: state.nav,
});

const mapDispatchToProps = dispatch => ({
  profileActions: bindActionCreators(profileActionCreator, dispatch),
  intlActions: bindActionCreators(intlActionCreator, dispatch),
  authActions: bindActionCreators(authActionCreator, dispatch),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(connectActionSheet(MyScreen));

const Styles = StyleSheet.create({
  container: {
    ...ThemeStyles.Color.background.white,
    paddingHorizontal: getRealSize(15),
  },
  profileContainer: {
    backgroundColor: '#F7F7F7',
    borderRadius: getRealSize(8),
    marginTop: getRealSize(15),
    flexDirection: 'row',
    padding: getRealSize(20),
    alignItems: 'center',
    justifyContent: 'center',
  },
  profileAvatar: {
    width: getRealSize(56),
    height: getRealSize(56),
    borderRadius: getRealSize(56),
    borderWidth: getRealSize(2),
    borderColor: '#fff',
    backgroundColor: '#e2e2e2',
  },
  profileContent: {
    flex: 1,
    marginLeft: getRealSize(8),
  },
  profileTitle: {},
  profileExtra: {},
  bottomBarContainer: {
    marginTop: getRealSize(12),
  },
  bottomLabel: {
    fontSize: getRealSize(8),
  },
});
